//
//  MonitorEditVC.m
//  UHealth
//
//  Created by gjtxz on 15/3/23.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "MonitorEditVC.h"

#define kFieldJX    40.f

@interface MonitorEditVC ()

@property (nonatomic,strong) UITextField            *fieldNickName;//昵称
@property (nonatomic,strong) UITextField            *fieldAccount;//账户
@property (nonatomic,strong) UITextField            *fieldPswd;//密码
@property (nonatomic,strong) UISwitch               *abnormalSwitch;//异常提醒开关

@property (nonatomic,strong) NSDictionary           *dataDic;
@property (nonatomic)        BOOL                   isAdd;

@end

@implementation MonitorEditVC

-(id)initWithData:(id)data isAdd:(BOOL)isAdd
{
    _dataDic = data;
    _isAdd = isAdd;
    self = [super init];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = kBacColor;
//        self.navigationItem.title = kLocal(@"add_monitor");
        [self setHidesBottomBarWhenPushed:YES];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NavView * nav = [[NavView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, kNavHeight) andTitleStr:kLocal(@"add_monitor") andVC:self];
    [self.view addSubview:nav];
    NSArray *plaArr = @[kLocal(@"nick_name"),
                        kLocal(@"monitor_account"),
                        kLocal(@"account_pw"),
                        kLocal(@"accept_monitor_msg")];
    _fieldNickName = [[UITextField alloc]init];
    _fieldAccount = [[UITextField alloc]init];
    _fieldPswd = [[UITextField alloc]init];
    _fieldPswd.secureTextEntry = YES; //密码
    _abnormalSwitch = [[UISwitch alloc]init];
    
    if (!_isAdd) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:kLocal(@"delete") style:UIBarButtonItemStylePlain target:self action:@selector(btnClick:)];
        self.navigationItem.rightBarButtonItem.tag = 2;
        _fieldNickName.text = _dataDic[@"mem_name"];
        
        NSArray *fArr = @[_fieldNickName,_fieldAccount,_fieldPswd,_abnormalSwitch];
        for (int i = 0; i < 2; i++) {
            
            UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, (i+1)*kFieldJX+kNavHeight, WIDTH, 0.5)];
            lineView.backgroundColor = [UIColor grayColor];
            [self.view addSubview:lineView];
            if (i == 1) {
                UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(20, i*kFieldJX+kNavHeight,250, kFieldJX)];
                l.text = plaArr[i];
                [self.view addSubview:l];
                _abnormalSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(WIDTH - 49 -15, (kFieldJX-31)/2 + i*kFieldJX+kNavHeight, 49, 31)];
                [_abnormalSwitch setOn:[_dataDic[@"ismessage"] boolValue]];
                [self.view addSubview:_abnormalSwitch];
            }else{
                UITextField *field = fArr[i];
                field.frame = CGRectMake(20, i*kFieldJX+kNavHeight, WIDTH-40, 40);
                field.placeholder = plaArr[i];
                field.clearButtonMode = UITextFieldViewModeWhileEditing;
                [self.view addSubview:field];
            }
        }
        UILabel *l1 = [[UILabel alloc]initWithFrame:CGRectMake(20, kFieldJX*2+10+kNavHeight, WIDTH-40, 21)];
        l1.font = [UIFont systemFontOfSize:14];
        l1.text = kLocal(@"add_yourself");
        l1.textColor = [UIColor grayColor];
        [self.view addSubview:l1];
        
    }else{
        NSArray *fArr = @[_fieldNickName,_fieldAccount,_fieldPswd,_abnormalSwitch];
        for (int i = 0; i < 4; i++) {
            
            UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, (i+1)*kFieldJX+kNavHeight, WIDTH, 0.5)];
            lineView.backgroundColor = [UIColor grayColor];
            [self.view addSubview:lineView];
            if (i == 3) {
                UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(20, i*kFieldJX+kNavHeight,250, kFieldJX)];
                l.text = plaArr[i];
                [self.view addSubview:l];
                _abnormalSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(WIDTH - 49 -15, (kFieldJX-31)/2 + i*kFieldJX+kNavHeight, 49, 31)];
                
                [self.view addSubview:_abnormalSwitch];
            }else{
                UITextField *field = fArr[i];
                field.frame = CGRectMake(20, i*kFieldJX+kNavHeight, WIDTH-40, 40);
                field.placeholder = plaArr[i];
                field.clearButtonMode = UITextFieldViewModeWhileEditing;
                [self.view addSubview:field];
            }
        }
        UILabel *l1 = [[UILabel alloc]initWithFrame:CGRectMake(20, kFieldJX*4+10+kNavHeight, WIDTH-40, 21)];
        l1.font = [UIFont systemFontOfSize:14];
        l1.text = kLocal(@"add_yourself");
        l1.textColor = [UIColor grayColor];
        [self.view addSubview:l1];
    }
    

    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(40, kFieldJX*4+100+kNavHeight, WIDTH - 80, 40);
    [saveBtn setTitle:kLocal(@"save_btn") forState:UIControlStateNormal];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn.layer setMasksToBounds:YES];
    [saveBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
    saveBtn.backgroundColor = kBlueColor;
    saveBtn.tag = 101;
    [self.view addSubview:saveBtn];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)btnClick:(UIButton *)btn
{
    if (btn.tag ==2) {//删除
        if (!kNetID) {
            [[iToast makeText:kLocal(@"notLogin")] show];
            return ;
        }
        if (!kNetIsOK) {
            [[iToast makeText:kLocal(@"netNoOk")] show];
            return ;
        }
        //默认用户famid的网络数据
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer.timeoutInterval = 5;
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
        NSString *postStr = [NSString stringWithFormat:@"%@/action/json/guardian.jsp?",kBaseUrl];
        NSDictionary *parameters = @{@"action"          : @"setGuardianDel",
                                     @"userid"          :[NSString stringWithFormat:@"%ld",(long)kNetID],
                                     @"guardian_id"     :_dataDic[@"guardian_id"],
                                     @"mobile_type"     :@"2",
                                     @"fromtype"        :@"1",
                                     @"app_line"        :kAPPLine};
        
        [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            kDebug(@"Success: %@", operation.responseString);
            BOOL type = [[responseObject objectForKey:@"type"] boolValue];
            if(type){//成功
                if (_block) {
                    _block();
                }
                [self.navigationController popViewControllerAnimated:YES];
            }else{
            }
            [[iToast makeText:responseObject[@"msg"]]show];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            kDebug(@"Error: %@", error);
            [[iToast makeText:kLocal(@"netError")] show];
        }];
        
    }else if(btn.tag == 101){
        NSString *nickName =_fieldNickName.text;
        NSString *account =_fieldAccount.text;
        NSString *pswd =_fieldPswd.text;
        if ( _isAdd&&(nickName.length>30||nickName.length<1 || account.length <1|| account.length>30 || pswd.length <6||pswd.length>12)){
            [[iToast makeText:kLocal(@"fill_in_correct")] show];
            return;
        }
        if ( !_isAdd && (nickName.length>30||nickName.length<1 )){
            [[iToast makeText:kLocal(@"fill_in_correct")] show];
            return;
        }
        
        if (!kNetID) {
            [[iToast makeText:kLocal(@"notLogin")] show];
            return ;
        }
        if (!kNetIsOK) {
            [[iToast makeText:kLocal(@"netNoOk")] show];
            return ;
        }
        //默认用户famid的网络数据
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer.timeoutInterval = 5;
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
        NSString *postStr = [NSString stringWithFormat:@"%@/action/json/guardian.jsp?",kBaseUrl];
        NSDictionary *parameters;
        if (_isAdd) {//添加
            parameters = @{@"action": @"setGuardian",
                           @"userid":[NSString stringWithFormat:@"%ld",kNetID],
                           @"mem_username":_fieldAccount.text,
                           @"mem_password":_fieldPswd.text,
                           @"mem_name":_fieldNickName.text,
                           @"ismessage":[NSString stringWithFormat:@"%d",_abnormalSwitch.isOn],
                           @"mobile_type":@"2",
                           @"fromtype":@"1",
                           @"app_line":kAPPLine};
        }else{//编辑
            parameters = @{@"action": @"setGuardianEdit",
                           @"userid":[NSString stringWithFormat:@"%ld",kNetID],
                           @"guardian_id":_dataDic[@"guardian_id"],
                           @"mem_name":_fieldNickName.text,
                           @"ismessage":[NSString stringWithFormat:@"%d",_abnormalSwitch.isOn],
                           @"mobile_type":@"2",
                           @"fromtype":@"1",
                           @"app_line":kAPPLine};
        }
        
        
        [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            kDebug(@"Success: %@", operation.responseString);
            BOOL type = [[responseObject objectForKey:@"type"] boolValue];
            if(type){//成功
                if (_block) {
                    _block();
                }
                [self.navigationController popViewControllerAnimated:YES];
            }else{
            }
            [[iToast makeText:responseObject[@"msg"]]show];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            kDebug(@"Error: %@", error);
            [[iToast makeText:kLocal(@"netError")] show];
        }];

        
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
